package com.df.bpm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.df.bpm.dto.BusinessInformationDTO4CreateWithOutput;
import com.df.bpm.dto.BusinessInformationDTO4Search;
import com.df.bpm.dto.BusinessLocationsDTO4Subset;
import com.df.bpm.dto.SequenceUpdaterDTO;
import com.df.bpm.entity.*;
import com.df.bpm.service.impl.*;
import com.df.common.entity.Pagination;
import com.df.common.utils.CommonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;


/**
 * 业务大全控制器
 * V2
 */
@Slf4j
@Tag(name = "业务大全控制器V2")
@RequestMapping("/businessInformationV2")
@RequiredArgsConstructor
@RestController
@SaCheckLogin
public class BusinessInformationControllerV2 {
    /**
     * 业务输出物服务
     */
    private final BusinessOutputsServiceImpl businessOutputsServiceImpl;

    /**
     * 业务输入物服务
     */
    private final BusinessInputsServiceImpl businessInputsServiceImpl;

    /**
     * 业务定位服务
     */
    private final BusinessLocationsServiceImpl businessLocationsServiceImpl;

    /**
     * 业务服务
     */
    private final BusinessInformationServiceImpl businessInformationServiceImpl;

    /**
     * 信息化申请单与业务关联关系服务
     */
    private final InformatizationRequirementBusinessesServiceImpl informatizationRequirementBusinessesServiceImpl;

    private final BusinessInformationDTO4SearchServiceImpl businessInformationDTO4SearchServiceImpl;

    /**
     * 刷新业务输出物输入物
     * <P>从子级过滤中间件后整理添加（不删除）<P/>
     * @param businessInformationIndex 要刷新的业务id
     * @return
     */
    @Operation(summary = "刷新业务输出物输入物", description = "从子级过滤中间件后整理添加（不删除）")
    @GetMapping("freshBusinessEntities")
    @SaIgnore
    public ResponseEntity<?> freshBusinessEntities(@RequestParam Integer businessInformationIndex) {
        businessInformationServiceImpl.freshBusinessEntities(businessInformationIndex);
        return ResponseEntity.ok().build();
    }

    /**
     * 按输出物id查询目标业务并扩展担当者名称
     * @param outputsEntityId 输出物实体ID
     * @return 扩展了担当者名称的业务DTO列表
     */
    @Operation(summary = "按输出物id查询目标业务并扩展担当者名称", description = "按输出物id查询目标业务并扩展担当者名称")
    @GetMapping("businessInformationDTO/outputsEntityId")
    @SaIgnore
    public ResponseEntity<?> getBusinessDto(Pagination pagination,@RequestParam Integer outputsEntityId) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessOutputsServiceImpl.getBusinessDto(outputsEntityId)));
        } else {

            return ResponseEntity.ok(businessOutputsServiceImpl.getBusinessDto(outputsEntityId));
        }
    }

    /**
     * 按目标业务id查询输出物清单
     * @param businessInformationIndex 目标业务id
     * @return 输出物Dto
     */
    @Operation(summary = "按目标业务id查询输出物清单", description = "按目标业务id查询输出物清单")
    @GetMapping("businessOutputDto/businessId")
    @SaIgnore
    public ResponseEntity<?> getBusinessOutputDto(Pagination pagination,@RequestParam Integer businessInformationIndex) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessOutputsServiceImpl.getOutputDto(businessInformationIndex)));
        } else {

            return ResponseEntity.ok(businessOutputsServiceImpl.getOutputDto(businessInformationIndex));
        }
    }

    /**
     * 按目标业务id查询输入物清单
     * @param businessInformationIndex  目标业务id
     * @return  输入物Dto
     */
    @Operation(summary = "按目标业务id查询输入物清单", description = "按目标业务id查询输入物清单")
    @GetMapping("businessInputDto/businessId")
    @SaIgnore
    public ResponseEntity<?> getBusinessInputDto(Pagination pagination,@RequestParam Integer businessInformationIndex) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessInputsServiceImpl.getInputDto(businessInformationIndex)));
        } else {

            return ResponseEntity.ok(businessInputsServiceImpl.getInputDto(businessInformationIndex));
        }
    }

    /**
     * 按目标业务id查询子级分组
     * @param superior 目标业务id（父级id）
     * @return 分组id清单
     */
    @Operation(summary = "按目标业务id查询子级分组", description = "按目标业务id查询子级分组")
    @GetMapping("groupId/superior")
    @SaIgnore
    public ResponseEntity<?> getGroupId4Steps(Pagination pagination,@RequestParam Integer superior) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessLocationsServiceImpl.getGroups(superior)));
        } else {

            return ResponseEntity.ok(businessLocationsServiceImpl.getGroups(superior));
        }
    }

    /**
     * 查询目标业务目标分组子级流程列表
     * @param superior  目标业务id
     * @param groupId   目标分组id
     * @return  子集业务流程
     */
    @Operation(summary = "查询目标业务目标分组子级流程列表", description = "查询目标业务目标分组子级流程列表")
    @GetMapping("businessLocationsDTO4Subset/superiorAndGroupId")
    @SaIgnore
    public ResponseEntity<?> getSteps(Pagination pagination,@RequestParam Integer superior, @RequestParam Integer groupId) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessLocationsServiceImpl.getStepDto(superior,groupId)));
        } else {

            return ResponseEntity.ok(businessLocationsServiceImpl.getStepDto(superior,groupId));
        }
    }

    /**
     * 通过详细信息模糊查询业务列表
     * @param pagination
     * @param temp 包含详细信息的业务DTO线索
     * @return  包含详细信息的业务DTO列表
     */
    @Operation(summary = "通过详细信息模糊查询业务列表", description = "通过详细信息模糊查询业务列表")
    @GetMapping("businessInformationDTO4Search")
    @SaIgnore
    public ResponseEntity<?> getBusinessInformationDTO4Search(Pagination pagination, BusinessInformationDTO4Search temp) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessInformationDTO4SearchServiceImpl.getList4Like(temp)));
        } else {

            return ResponseEntity.ok(businessInformationDTO4SearchServiceImpl.getList4Like(temp));
        }
    }



    /**
     * 查询业务定位信息
     * @param pagination
     * @param temp 业务定位线索
     * @return  业务定位列表
     */
    @Operation(summary = "通过详细信息模糊查询业务列表", description = "通过详细信息模糊查询业务列表")
    @GetMapping("businessLocationsDTO4Subset")
    @SaIgnore
    public ResponseEntity<?> getBusinessLocations(Pagination pagination, BusinessLocationsDTO4Subset temp) {
        if (CommonUtils.varIsNotBlank(pagination.getPageNum(), pagination.getPageSize())) {
            PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
            return ResponseEntity.ok(new PageInfo<>(businessLocationsServiceImpl.getList4Like(temp)));
        } else {

            return ResponseEntity.ok(businessLocationsServiceImpl.getList4Like(temp));
        }
    }

    /**
     * 新增业务
     * @param newBusinessDto   业务信息DTO(扩展输出物实体ID)
     * @return  新增成功后的业务信息id
     */
    @Operation(summary = "新增业务", description = "填写业务名称、担当主体ID（实体类）、申请单ID 以便新增业务")
    @PostMapping("")
    @SaIgnore
    public ResponseEntity<?> newBusiness(@RequestBody BusinessInformationDTO4CreateWithOutput newBusinessDto) {
        if(CommonUtils.varIsBlank(newBusinessDto.getBusinessInformationIndex())){
            businessInformationServiceImpl.add(newBusinessDto);
        }
        try {
            InformatizationRequirementBusinesses newRelation=new InformatizationRequirementBusinesses();
            newRelation.setBusinessInformationIndex(newBusinessDto.getBusinessInformationIndex());
            newRelation.setInformatizationRequirementIndex(newBusinessDto.getInformatizationRequirementIndex());
            informatizationRequirementBusinessesServiceImpl.add(newRelation);
        }catch (Exception ignored){
        }
        if(CommonUtils.varIsNotBlank(newBusinessDto.getBusinessEntityIndex4Output())){
            BusinessOutputs temp=new BusinessOutputs();
            temp.setBusinessInformationIndex(newBusinessDto.getBusinessInformationIndex());
            temp.setBusinessEntityIndex(newBusinessDto.getBusinessEntityIndex4Output());
            businessOutputsServiceImpl.add(temp);
        }
        return ResponseEntity.ok(newBusinessDto.getBusinessInformationIndex());
    }

    /**
     * 更新业务
     * @param newBusiness   业务基本信息
     * @return  更新行数
     */
    @Operation(summary = "更新业务", description = "更改目标业务的 业务名称、担当主体ID（实体类）、申请单ID")
    @PutMapping("")
    @SaIgnore
    public ResponseEntity<?> updateBusiness(@RequestBody BusinessInformation newBusiness) {
        int rows=0;
        if(CommonUtils.varIsBlank(newBusiness.getBusinessInformationIndex())){
            rows+=businessInformationServiceImpl.add(newBusiness);
        }else{
            rows+=businessInformationServiceImpl.update(newBusiness);
        }
        try {
            InformatizationRequirementBusinesses newRelation=new InformatizationRequirementBusinesses();
            newRelation.setBusinessInformationIndex(newBusiness.getBusinessInformationIndex());
            newRelation.setInformatizationRequirementIndex(newBusiness.getInformatizationRequirementIndex());
            rows+=informatizationRequirementBusinessesServiceImpl.add(newRelation);
        }catch (Exception ignored){
        }
        return ResponseEntity.ok(rows);
    }

    /**
     * （业务信息）调整顺序
     * <P>head2Tail;head=old,tail=new</P>
     * @param temp 业务顺序变更信息
     * @return 更改结果
     */
    @Operation(summary = "（业务信息）调整顺序", description = "（业务信息）调整顺序")
    @PutMapping("businessLocations/sequence")
    @SaIgnore
    public ResponseEntity<?> updateSequence(@RequestBody SequenceUpdaterDTO temp){
        Integer headSequence=temp.getHeadSequence();
        Integer tailSequence=temp.getTailSequence();
        Integer superior=temp.getSuperior();
        Integer groupID=temp.getGroupID();

        if(headSequence.equals(tailSequence)){
            return ResponseEntity.ok(0);
        }
        BusinessLocations head=businessLocationsServiceImpl.getOne(new BusinessLocations()
                .setSuperior(superior)
                .setGroupID(groupID)
                .setSequence(headSequence));
        int Length=1;
        if(headSequence<tailSequence){
            Length=-1;
        }
        businessLocationsServiceImpl.updateSequences(Length,headSequence,tailSequence,superior,groupID);
        businessLocationsServiceImpl.update(new BusinessLocations()
                .setBusinessLocationsIndex(head.getBusinessLocationsIndex())
                .setSequence(tailSequence));
        return ResponseEntity.ok(1);
    }

    /**
     * 更新业务定位
     * @param temp  业务定位信息BusinessLocations
     * @return  更新行数
     */
    @Operation(summary = "更新业务定位", description = "更改目标业务上下游定位（父级id、分组、顺序）")
    @PutMapping("businessLocations")
    @SaIgnore
    public ResponseEntity<?> updateLocation(@RequestBody BusinessLocations temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessLocationsIndex())){
            businessLocationsServiceImpl.insertSequence(temp);
        }else {
            businessLocationsServiceImpl.updateWithAutoSequence(temp);
        }
        return ResponseEntity.ok(1);
    }

    /**
     * 新增业务定位
     * @param temp  业务定位信息BusinessLocations
     * @return  更新成功的定位信息
     */
    @Operation(summary = "新增业务定位", description = "新增目标业务上下游定位（父级id、分组、顺序）")
    @PostMapping("businessLocations")
    @SaIgnore
    public ResponseEntity<?> addLocation(@RequestBody BusinessLocations temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessLocationsIndex())){
            businessLocationsServiceImpl.insertSequence(temp);
        }else {
            businessLocationsServiceImpl.updateWithAutoSequence(temp);
        }
        return ResponseEntity.ok(temp);
    }

    /**
     * 更新业务输出物
     * @param temp  输出物信息
     * @return  更新行数
     */
    @Operation(summary = "更新业务输出物", description = "更改目标业务输出物")
    @PutMapping("businessOutputs")
    @SaIgnore
    public ResponseEntity<?> updateOutputs(@RequestBody BusinessOutputs temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessOutputsIndex())){
            return ResponseEntity.ok(businessOutputsServiceImpl.add(temp));
        }
        return ResponseEntity.ok(businessOutputsServiceImpl.update(temp));
    }

    /**
     * 新增业务输出物
     * @param temp  输出物信息
     * @return  更新成功的输出物
     */
    @Operation(summary = "新增业务输出物", description = "新增目标业务输出物")
    @PostMapping("businessOutputs")
    @SaIgnore
    public ResponseEntity<?> addOutputs(@RequestBody BusinessOutputs temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessOutputsIndex())){
            businessOutputsServiceImpl.add(temp);
        }else {
            businessOutputsServiceImpl.update(temp);
        }
        return ResponseEntity.ok(temp);
    }

    /**
     * 更新业务输入物
     * @param temp  输入物信息
     * @return  更新行数
     */
    @Operation(summary = "更新业务输入物", description = "更改目标业务输入物")
    @PutMapping("businessInputs")
    @SaIgnore
    public ResponseEntity<?> updateInputs(@RequestBody BusinessInputs temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessInputsIndex())){
            return ResponseEntity.ok(businessInputsServiceImpl.add(temp));
        }
        return ResponseEntity.ok(businessInputsServiceImpl.update(temp));
    }

    /**
     * 新增业务输入物
     * @param temp  输入物信息
     * @return  更新成功的输入物
     */
    @Operation(summary = "新增业务输入物", description = "新增目标业务输入物")
    @PostMapping("businessInputs")
    @SaIgnore
    public ResponseEntity<?> addInputs(@RequestBody BusinessInputs temp) {
        if(CommonUtils.varIsBlank(temp.getBusinessInputsIndex())){
            businessInputsServiceImpl.add(temp);
        }else{
            businessInputsServiceImpl.update(temp);
        }
        return ResponseEntity.ok(temp);
    }


    /**
     *  删除业务定位
     * @param businessLocationsIndex    定位id
     * @return  删除行数
     */
    @Operation(summary = "删除业务定位", description = "删除上下游定位")
    @DeleteMapping("businessLocationsIndex")
    @SaIgnore
    public ResponseEntity<?> deleteBusinessLocations(@RequestParam Integer businessLocationsIndex) {
        BusinessLocations temp=businessLocationsServiceImpl.getById(businessLocationsIndex);
        temp.setSequence(9999);
        businessLocationsServiceImpl.updateWithAutoSequence(temp);// 排序后再删
        return ResponseEntity.ok(businessLocationsServiceImpl.delete(Collections.singleton(businessLocationsIndex)));
    }

    /**
     * 删除目标业务输出物
     * @param businessOutputsIndex  输出物id
     * @return  删除行数
     */
    @Operation(summary = "删除目标业务输出物 ", description = "删除目标业务输出物 ")
    @DeleteMapping("businessOutputsIndex")
    @SaIgnore
    public ResponseEntity<?> deleteBusinessOutputs(@RequestParam Integer businessOutputsIndex) {
        return ResponseEntity.ok(businessOutputsServiceImpl.delete(Collections.singleton(businessOutputsIndex)));
    }

    /**
     * 删除目标业务输入物
     * @param businessInputsIndex  输出物id
     * @return  删除行数
     */
    @Operation(summary = "删除目标业务输入物 ", description = "删除目标业务输入物 ")
    @DeleteMapping("businessInputsIndex")
    @SaIgnore
    public ResponseEntity<?> deleteBusinessInputs(@RequestParam Integer businessInputsIndex) {
        return ResponseEntity.ok(businessInputsServiceImpl.delete(Collections.singleton(businessInputsIndex)));
    }

    /**
     * 完整删除业务
     * @param businessInformationIndex  目标业务id
     * @return  删除行数
     */
    @Operation(summary = "按业务id完整删除（包括输出、输入、上下游定位） ", description = "按业务id完整删除（包括输出、输入、上下游定位） ")
    @DeleteMapping("entirelyById")
    @SaIgnore
    public ResponseEntity<?> deleteBusiness(@RequestParam Integer businessInformationIndex) {
        int rows=0;
        rows+=businessInformationServiceImpl.delete(Collections.singleton(businessInformationIndex));
        QueryWrapper<BusinessLocations> wrapper4Location=new QueryWrapper<>();
        wrapper4Location.eq("businessInformationIndex", businessInformationIndex);
        rows+=this.businessLocationsServiceImpl.delete(wrapper4Location);
        QueryWrapper<BusinessOutputs> wrapper4Output=new QueryWrapper<>();
        wrapper4Output.eq("businessInformationIndex", businessInformationIndex);
        rows+=this.businessOutputsServiceImpl.delete(wrapper4Output);
        QueryWrapper<BusinessInputs> wrapper4Input=new QueryWrapper<>();
        wrapper4Input.eq("businessInformationIndex", businessInformationIndex);
        rows+=this.businessInputsServiceImpl.delete(wrapper4Input);
        return ResponseEntity.ok(rows);
    }

}
